package com.zh.springcloud.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: jwt token 扩展信息
 * @ClassName JwtTokenEnhancer
 * @date: 2021.11.28 18:52
 * @Author: zhanghang
 */
public class JwtTokenEnhancer implements TokenEnhancer {


	@Override
	public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
		System.out.println("====jwt 扩展信息====");
		System.out.println(accessToken.getExpiration());
		// 可以获取登录用户的账号，权限等信息，
		System.out.println(authentication.getName());
		Object principal = authentication.getUserAuthentication().getPrincipal();
		JSONObject jb  = JSON.parseObject(JSON.toJSONString(principal));
		System.out.println(jb.get("username"));
		// 扩展信息是放入到DefaultOAuth2AccessToken中的additionalInformation 里面
		Map<String, Object> map = new HashMap<>();
		map.put("custom","自定义信息");
		DefaultOAuth2AccessToken accessToken1 = (DefaultOAuth2AccessToken) accessToken;
		accessToken1.setAdditionalInformation(map);
		return accessToken1;
	}
}
